<template>
  <van-field
    v-if="h5"
    v-show="designer || (item.options && !item.options.hidden)"
    v-model="fieldModel"
    type="number"
    :name="item.options && item.options.name"
    :label="item.options && item.options.label"
    :disabled="item.options && item.options.disabled"
    :readonly="isDetail || designer || (item.options && item.options.readonly)"
    :placeholder="isDetail ? '' : item.options && item.options.placeholder"
    :required="item.options && !isDetail && item.options.required"
    :rules="isDetail ? [] : rules"
    :border="false"
    :label-width="item.options?.labelPosition === 'top' ? '100%' : undefined"
    :label-align="(item.options && item.options.labelPosition) || undefined"
    :input-align="(item.options && item.options.inputAlign) || undefined"
    autocomplete="off"
    @blur="limitInput(fieldModel)"
  >
    <template v-if="append" #button>
      {{ append }}
    </template>
  </van-field>
  <widget-form-item
    v-else
    v-show="designer || (item.options && !item.options.hidden)"
    :designer="designer"
    :widget-list="widgetList"
    :item="item"
    :rules="isDetail ? [] : rules"
    :index="index"
    :show-message="!isDetail"
  >
    <el-input
      v-if="!isDetail"
      v-model="fieldModel"
      type="number"
      :disabled="item.options && item.options.disabled"
      :readonly="designer || (item.options && item.options.readonly)"
      :placeholder="item.options && item.options.placeholder"
      :min="item.options && item.options.min"
      :max="item.options && item.options.max"
      @blur="limitInput(fieldModel)"
    >
      <template v-if="append" #append>{{ append }}</template>
    </el-input>
    <div v-else>
      {{ fieldModel }}
      <span v-if="append" style="padding-left: 8px">{{ append }}</span>
    </div>
  </widget-form-item>
</template>

<script>
import { ref, computed } from 'vue'
import props from './props'
import field from './field'

export default {
  name: 'MInput',
  props,
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const append = computed(() => {
      if (props.item.options.append) {
        return props.item.options.append
      }
      return ''
    })

    /** 当number类型时限制输入大小范围 */
    const limitInput = (val) => {
      const limitMin = props.item.options.min || 0
      const limitMax = props.item.options.max || 9
      if (val > limitMax) {
        emit('update:modelValue', limitMax)
        return false
      }
      if (val < limitMin) {
        emit('update:modelValue', limitMin)
        return false
      }
      return true
    }

    return {
      append,
      limitInput,
      ...field(props, emit)
    }
  }
}
</script>
